<script lang="ts" setup>
import { getMemberProfileAPI, uploadAvatar, putMemberProfileAPI } from '@/apis/profile';
import { useMemberStore } from '@/stores/modules/memberStore';
import { XtxRegionPickerInstance } from '@/types/component';
import { Gender, ProfileDetail } from '@/types/member';
import { onLoad } from '@dcloudio/uni-app';
import { ref } from 'vue';

const { safeAreaInsets } = uni.getSystemInfoSync();

const memberStore = useMemberStore();

// 详细个人信息
const profileDetail = ref<ProfileDetail>({} as ProfileDetail);
const getProfileDetail = async () => {
  const response = await getMemberProfileAPI().request;
  profileDetail.value = response.result;
};

// 头像修改事件
const onAvatarChange = async () => {
  if (profileDetail.value) {
    // 读取媒体文件获取路径
    const filePath = await new Promise<string>((resolve, reject) => {
      uni.chooseMedia({
        count: 1,
        mediaType: ['image'],
        success({ tempFiles }) {
          resolve(tempFiles[0].tempFilePath);
        },
        fail(error) {
          reject(error);
          uni.showToast({ icon: 'none', title: '无法访问媒体文件！' });
        },
      });
    });
    // 上传图片
    const { result } = await uploadAvatar(filePath).upload;
    profileDetail.value.avatar = result;
    uni.showToast({ icon: 'none', title: '头像上传成功！' });
  } else {
    getProfileDetail();
  }
};

// 性别修改事件
const onGenderChange: UniHelper.RadioGroupOnChange = e => {
  profileDetail.value!.gender = e.detail.value as Gender;
};

// 生日修改事件
const onBirthdayChange: UniHelper.DatePickerOnChange = e => {
  profileDetail.value!.birthday = e.detail.value;
};

// 地区修改事件
const regionPickerRef = ref<XtxRegionPickerInstance>();
const onRegionChange = (fullLocation: string) => {
  profileDetail.value!.fullLocation = fullLocation;
};

// 提交修改
const onProfileUpdate = async () => {
  const { nickname, gender, birthday, profession } = profileDetail.value;
  const { provinceCode, cityCode, countyCode } = regionPickerRef.value;
  const response = await putMemberProfileAPI({ nickname, gender, birthday, profession, provinceCode, cityCode, countyCode }).request;
  {
    // 完成处理
    const { avatar, nickname } = response.result;
    memberStore.setProfile({ avatar, nickname });
    uni.navigateBack({ complete: () => uni.showToast({ icon: 'success', title: '个人信息修改成功！' }) });
  }
};

onLoad(() => {
  getProfileDetail();
});
</script>

<template>
  <view class="viewport">
    <!-- 导航栏 -->
    <view class="navbar" :style="{ paddingTop: `${safeAreaInsets?.top}px` }">
      <navigator class="back icon-left" hover-class="none" open-type="navigateBack"></navigator>
      <view class="title">个人信息</view>
    </view>
    <!-- 头像 -->
    <view class="avatar">
      <view class="avatar-content">
        <image class="image" :src="profileDetail.avatar" mode="aspectFill" />
        <text class="text" @tap="onAvatarChange">点击修改头像</text>
      </view>
    </view>
    <!-- 表单 -->
    <view class="form">
      <view class="form-content">
        <view class="form-item">
          <text class="label">账号</text>
          <text class="account">{{ profileDetail.account }}</text>
        </view>
        <view class="form-item">
          <text class="label">昵称</text>
          <input class="input" type="text" placeholder="请设置昵称" v-model="profileDetail.nickname" />
        </view>
        <view class="form-item">
          <text class="label">性别</text>
          <radio-group @change="onGenderChange">
            <label class="radio">
              <radio value="男" color="#27ba9b" :checked="profileDetail.gender === '男'" />男
            </label>
            <label class="radio">
              <radio value="女" color="#27ba9b" :checked="profileDetail.gender === '女'" />女
            </label>
          </radio-group>
        </view>
        <view class="form-item">
          <text class="label">生日</text>
          <picker class="picker" mode="date" start="1900-01-01" :end="new Date()" :value="profileDetail.birthday"
            @change="onBirthdayChange">
            <view class="placeholder">{{ profileDetail.birthday || '请选择生日' }}</view>
          </picker>
        </view>
        <view class="form-item">
          <text class="label">地区</text>
          <XtxRegionPicker ref="regionPickerRef" class="picker" @change="onRegionChange"
            :fullLocation="profileDetail.fullLocation">
            <view class="placeholder">{{ profileDetail.fullLocation || '请选择地区' }}</view>
          </XtxRegionPicker>
        </view>
        <view class="form-item">
          <text class="label">职业</text>
          <input class="input" type="text" v-model="profileDetail.profession" placeholder="请输入职业" />
        </view>
      </view>
      <button class="form-button" @tap="onProfileUpdate">完成编辑</button>
    </view>
  </view>
</template>

<style lang="scss">
.viewport {
  width: 100vw;
  height: 100vh;
  background-color: #f4f4f4;
  background-image: url(https://pcapi-xiaotuxian-front-devtest.itheima.net/miniapp/images/order_bg.png);
  background-size: auto 420rpx;
  background-repeat: no-repeat;
  display: flex;
  flex-direction: column;
}

.navbar {
  position: relative;

  .back {
    position: absolute;
    width: 40px;
    height: 40px;
    left: 0;
    font-size: 20px;
    color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .title {
    height: 40px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 16px;
    font-weight: 500;
    color: #fff;
  }
}

.avatar {
  width: 100%;
  height: 260rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;

  .image {
    width: 160rpx;
    height: 160rpx;
    border-radius: 50%;
    background-color: #eee;
  }

  .text {
    display: block;
    padding-top: 20rpx;
    line-height: 1;
    font-size: 26rpx;
    color: #fff;
  }
}

.form {
  background-color: #f4f4f4;

  &-content {
    margin: 20rpx 20rpx 0;
    padding: 0 20rpx;
    border-radius: 10rpx;
    background-color: #fff;
  }

  &-item {
    padding: 25rpx 10rpx;
    height: 96rpx;
    background-color: #fff;
    line-height: 46rpx;
    font-size: 28rpx;
    border-bottom: 1rpx aolid #ddd;
    display: flex;

    &:last-child {
      border: none;
    }

    .label {
      width: 180rpx;
      color: #333;
    }

    .account {
      color: #666;
    }

    .input {
      flex: 1;
      display: block;
      height: 46rpx;
    }

    .radio {
      margin-right: 20rpx;
    }

    .picker {
      flex: 1;
    }

    .placeholder {
      color: #808080;
    }
  }

  &-button {
    margin: 30rpx 20rpx;
    height: 80rpx;
    text-align: center;
    background-color: #27ba9b;
    font-size: 30rpx;
    line-height: 80rpx;
    color: #fff;
    border-radius: 80rpx;
  }

}
</style>